/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.apkinstaller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;
import org.kymjs.kjframe.KJDB;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;

import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ProgressCallback;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppConfig;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.api.UrlConnect;
import com.talben.soudian.bean.ApkDetail;
import com.talben.soudian.bean.User;
import com.talben.soudian.service.ScoreService;

/**
 * @Title: ApkTaskManager.java
 * @Package com.talben.soudian.apkinstaller
 * @Description: 下载和安装事务
 * @author Tal.Ben
 * @date 2015年6月1日 上午11:52:28
 * @version v1.0
 */
public class ApkTaskManager{
	
	private Context mContext;
	
	private ApkDetail apkDetail;
	
	//进度条
	private ProgressDialog mProgressDialog;
	
	public ApkTaskManager(Context mContext, ApkDetail apkDetail) {
		super();
		this.mContext = mContext;
		this.apkDetail = apkDetail;
	}

	/**
	 * 下载文件
	 */
	public void downloadFile() {
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setTitle("下载中"+apkDetail.getName()+"...");
		mProgressDialog.setIcon(R.drawable.soudian_icon_48);
		mProgressDialog.setMessage("下载后请打开3-5分钟才能获取积分");
		mProgressDialog.setCancelable(false);   // 设置是否可以通过点击Back键取消
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.show();
		Ion.with(mContext)
		   .load(UrlConnect.HOST + apkDetail.getDownloadUrl())
		   .progressDialog(mProgressDialog)
		   .progress(new ProgressCallback() {
				
				@Override
				public void onProgress(long arg0, long arg1) {
					//System.out.println("" + arg0 + " / " + arg1);
					//mProgressDialog.setMax(Integer.parseInt(String.valueOf(arg1)));
					//mProgressDialog.setProgress(Integer.parseInt(String.valueOf(arg0)));
				}
			})
			.write(new File(AppConfig.DEFAULT_SAVE_FILE_PATH+apkDetail.getName()))
			.setCallback(new FutureCallback<File>() {
				
				@Override
				public void onCompleted(Exception e, File file) {
					mProgressDialog.cancel();
					if (e == null) {
						//安装apk
						TDevice.installAPK(mContext, file);
						//保存到数据库
						KJDB db = KJDB.create(mContext);
						apkDetail.setBtnStatus("安装");
						db.save(apkDetail);
						User user = AppContext.getInstance().getLoginUser();
						//获取分数的service
						if (user.getuPhone() != null) {
							Intent intent = new Intent(mContext, ScoreService.class);
							intent.putExtra("appname", apkDetail.getName());
							intent.putExtra("id", apkDetail.getServerId());
							intent.putExtra("pkgName", apkDetail.getPackageName());
							intent.putExtra("account", user.getuPhone());
							List<ApkDetail> apkList = db.findAllByWhere(ApkDetail.class, "packageName='"+apkDetail.getPackageName()+"'");
							//context.startService(intent);
							for (ApkDetail apkInstalled : apkList) {
								int opentimes = apkInstalled.getOpentimes();
								int opencount = apkInstalled.getOpencount();
								if ((++opencount) % opentimes == 0) {
									apkInstalled.setOpencount(opencount);
									db.update(apkInstalled);
									SouDianAPI.getScore(AppContext.getInstance().getLoginUser().getuPhone(), apkDetail.getServerId() , mHandler);
								}
							}
						}
					}
				}
			});
	}
	
	public static final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
            try {
				String msg = new String(arg2,"utf-8");
				AppContext.showToast(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				Thread.sleep(240000);
				String result = new String(arg2,"utf-8");
				JSONObject jObj = new JSONObject(result);
				if (jObj.getString("result").equals("success")) {
					AppContext.showToast("恭喜你，获取了"+jObj.getString("score")+"分");;
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
	
}

